package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.service.impl.OrderServiceImpl;
import com.authine.cloudpivot.ext.utils.EncryptUtils;
import com.authine.cloudpivot.ext.utils.RegexUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.cloudpivot.ext.vo.CustomerOrderVo;
import com.authine.cloudpivot.ext.vo.OrderVo;
import com.authine.cloudpivot.ext.vo.i.IOrderCustomerVO;
import com.authine.cloudpivot.ext.vo.i.IOrderVendorGoodsVO;
import com.authine.cloudpivot.ext.vo.i.IOrderVendorVO;
import com.authine.common.util.ObjectMapperUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.hermes.lib.cloudpivot.cache.core.lock.MultiRetryLock;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.rpc.SaveOrUpdateBO;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Path("OrderController")
@Slf4j
public class OrderController extends ApplicationService {

    private OrderService orderService = new OrderServiceImpl();
    TransactionTemplate transactionTemplate = ApplicationContextUtils.getBean(TransactionTemplate.class);

    @Path("custCreateOrder")
    @POST
    @Operation(summary = "订单-提交客户订单", tags = CUSTOM_SERVICE, description = "")
    public SingleResponse custCreateOrder(SaveOrUpdateBO saveOrUpdateBO) {

        SingleResponse res = SingleResponse.buildFailure("-1", "失败");

        Map<String, Object> data = saveOrUpdateBO.getData();

        if (null == saveOrUpdateBO) {
            res.setErrMessage("参数问题");
            return res;
        }
        String erp_po = (String) data.get("erp_po");

        if (!StringUtils.between(erp_po, 0, 50)) {
            res.setErrMessage("ERP PO 单号不正确");
            return res;
        }
        String receiver = (String) data.get("receiver");

        if (StringUtils.isBlank(receiver) || !StringUtils.between(receiver, 1, 50)) {
            res.setErrMessage("收货人不正确");
            return res;
        }
        String phone = (String) data.get("phone");

        if (StringUtils.isBlank(phone) || !StringUtils.between(phone, 1, 50)) {
            res.setErrMessage("电话不正确");
            return res;
        }
        String address = (String) data.get("address");

        if (StringUtils.isBlank(address) || !StringUtils.between(address, 1, 500)) {
            res.setErrMessage("地址不正确");
            return res;
        }
        String postal = (String) data.get("postal");
        if (StringUtils.isBlank(postal)) {
            postal = "";
        } else if (!StringUtils.between(postal, 0, 50)) {
            res.setErrMessage("邮编不正确");
            return res;
        }

        //提交订单处理

        SingleResponse singleResponse = orderService.orderBeforCondition(data);

        if (singleResponse.isSuccess()) {
            SingleResponse execute = transactionTemplate.execute(transactionStatus -> orderService.submitOrder(data));
            log.info("====================\n====================={}", execute);
            return execute;

        } else {
            return singleResponse;
        }
    }


    @Path("customerCreateOrder")
    @POST
    @Operation(summary = "订单-客户创建订单", tags = CUSTOM_SERVICE, description = "")
    public SingleResponse customerCreateOrder(@Nullable @RequestBody OrderVo order) {
        log.info("客户创建订单 入参:{}", order);
        if (order == null) return SingleResponse.buildFailure("-1", "参数为空");
        log.warn("[order-create] begin:执行类：{},执行方法：customerCreate（【客户】创建订单）,请求人{}" + this.getClass().getName(), RequestContext.getCorpLoginId());

        CustomerOrderVo orderVo = order.toCustomerOrderVo();

        IOrderCustomerVO orderCustomerVO = null;
        MultiRetryLock lock = null;

        try {

            if (orderVo.getCustomerOrderGoodsVo().stream().anyMatch(g -> g.getGoods_src() == null)) {
                return SingleResponse.buildFailure("-1", "商品来源类型不能为空");
            }
            String lockString;
            if (RegexUtils.notNull(orderVo.getClient_order_id())) {
                lockString = EncryptUtils.MD5_32(RequestContext.getCorpLoginId() + orderVo.getClient_order_id());
            } else {
                lockString = EncryptUtils.MD5_32(ObjectMapperUtils.toJSONString(orderVo)) + RequestContext.getCorpLoginId();
            }
            lock = new MultiRetryLock(lockString);
            try {
                lock.lock(30000l);
            } catch (Exception e) {
                lock = null;
                return SingleResponse.buildFailure("-1", "业务数据已在提交中，请勿重复提交！");
            }
            //创建订单
            orderCustomerVO = orderService.iCreateOrder(orderVo);
            //todo 通知事件

        } catch (Exception e) {
            log.error("订单创建异常:" + e.getMessage(), e);
            return SingleResponse.buildFailure("-1", "订单创建异常," + e.getMessage());
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }
        //异步调用晶科请购单完成方法

        // 返回客户订单
        Map<String, Object> map1 = getCustomerOrderMap(orderCustomerVO);
        log.warn("[order-create] end:执行类：{},执行方法：customerCreate（【客户】创建订单）,请求人{}" + this.getClass().getName(), RequestContext.getCorpLoginId());
        SingleResponse<Map<String, Object>> res = SingleResponse.of(map1);
        res.setErrMessage("订单创建成功");
        return res;
    }

    private Map<String, Object> getCustomerOrderMap(IOrderCustomerVO orderCUstomer) {
        log.warn("[biz-group] begin:执行类：{},执行方法：getCustomerOrderMap（客户订单Map）,请求人{}" + this.getClass().getName(), RequestContext.getCorpLoginId());
        List<Map> igResult = new ArrayList<>();
        for (IOrderVendorVO v : orderCUstomer.getOrderVendorVO()) {
            for (IOrderVendorGoodsVO o : v.getOrderVendorGoodsVO()) {
                Map<String, Object> map = new HashMap<>();
                map.put("clientOrderGoodsId", o.getClient_order_goods_id());
                map.put("orderGoodsId", o.getId());
                igResult.add(map);
            }
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("clientOrderId", orderCUstomer.getClient_order_id());
        map1.put("orderId", orderCUstomer.getId());
        map1.put("orderGoods", igResult);
        log.warn("[biz-group] end:执行类：{},执行方法：getCustomerOrderMap（客户订单Map）,请求人{}" + this.getClass().getName(), RequestContext.getCorpLoginId());
        return map1;
    }


}
